import { pageRecord, receiptRecord } from "../../service/api/api-instruct-record";
import { calculateDaysAgo } from "../../utils/util";
import Message from 'tdesign-miniprogram/message/index';
// pages/instruct/index.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentUser: {},//当前用户
    access: {} as any,// 当前用户权限
    instructList: [],//宣传指令的列表
    currentPage: 1, // 当前页数
    pageSize: 8, // 每页数据数量
    total: 0,//所有数据条数
    hasMoreData: true, // 是否还有更多数据
    firstReachBottom: 0,//是否第一次触底
    fabButton: {
      theme: "light"
    },//通讯录的按钮配置
    receiptVisible: false,//回执情况抽屉是否打开
    receiptList: [],//回执情况列表
    instructId: '',//指令id
    isLoadReceiptList: true,//是否正在加载回执情况列表

  },

  /**
  * 预备Tree结构数据
  * @param data
  */
  readyTreeData(data: AdminOrganizationData.Organization[]): any {
    const treeData = [];

    if (data) {
      data.forEach((val) => {
        if (val.isFolder === 1 && val.children === undefined) {
        } else {
          treeData.push({
            name: val.name,
            id: val.id,
            parentId: val.parentId,
            checkbox: true,
            isFolder: val.isFolder,
            isChildren: val.children === undefined ? 0 : 1,
            children: this.readyTreeData(val.children as AdminOrganizationData.Organization[]),
          });
        }
      });
    }
    return treeData;
  },
  /**
* 预备Tree结构数据
* @param data
*/
  readyTreeData2(dataTree: [], selectIds: []): any {
    if (dataTree.length > 0) {
      let list = dataTree.map(item => {
        if (item.isChildren == 1) {
          item.children = this.readyTreeData2(item.children, selectIds);
          let noChildren = item.children.filter((item) => item.checked === 0); //过滤出未选中的
          let noLength = noChildren.length;
          if (noLength == 0) { //未选中的 == 0 ，选中状态
            let pingChildren = item.children.filter((item) => item.checked === -1); //过滤出平的，未全选中
            let pingLength = pingChildren.length;
            if (pingLength == 0) {//平的 == 0，选中状态
              item.checked = 1;
            } else {//平的 != 0, 平状态 
              item.checked = -1;
            }
          } else if (noLength == item.children.length) { //未选中的 == 孩子长度，表示 父节点 未选中
            item.checked = 0;
          } else { //未选中的 >0 && < 孩子长度，表示 父节点 平的
            item.checked = -1;
          }
        } else {
          item.checked = selectIds.includes(item.id) ? 1 : 0
        }
        return item
      })
      return list;
    }
    return []
  },
  /**
  * 处理已选中的数据
  * @param data
  */
  readySelectData(data: AdminOrganizationData.Organization[]): any {
    const ids = [];
    function traverse(arr) {
      arr.forEach(item => {
        if (item.isView === 1) {
          ids.push(item.id);
        }
        if (item.children) {
          traverse(item.children);
        }
      });
    }
    traverse(data);
    return ids;
  },
  //加载回执情况列表
  async onLoadReceiptList(id) {
    const response = await receiptRecord({ id });
    if (response.code === 0) {
      this.setData({
        receiptList: this.readyTreeData(response.data),
        isLoadReceiptList: false
      })
      if (!this.data.isLoadReceiptList) {
        wx.hideLoading()
        this.setData({
          instructId: id,
          receiptVisible: true
        })
        this.setData({
          receiptList: this.readyTreeData2(this.data.receiptList, this.readySelectData(response.data))
        })

      }
    }
  },
  //打开查看回执情况抽屉
  onOpenReceipt(e) {
    this.onLoadReceiptList(e.currentTarget.dataset.id)
    wx.showLoading({
      title: "加载中"
    })

  },
  //关闭查看查看回执情况的抽屉
  closeReceipt() {
    this.setData({
      receiptVisible: false
    })
  },
  //点击通讯录
  handlePurple() {
    wx.navigateTo({
      url: "/pages/instruct/address/index"
    })
  },
  //发布指令
  handleCreate() {
    wx.navigateTo({
      url: "/pages/instruct/create/index"
    })
  },
  //获取宣传指令列表(分页)用于加载更多
  async getInstructListPage(params: { current: number, pageSize: number }) {
    wx.showLoading({
      title: '加载中...'
    })
    const response = await pageRecord({ current: params.current, pageSize: params.pageSize });
    const hasMoreData = response.data.total >= params.pageSize * params.current;
    const list = response.data.data
    list.forEach(item => {
      item.beforNow = calculateDaysAgo(item.createdTime)
    })
    if (response.code === 0) {
      this.setData({
        instructList: [...this.data.instructList, ...list],
        total: response.data.total,
        hasMoreData
      })
    }
    wx.hideLoading()
  },
  //页面刷新
  async getInstructList(params: { current: number, pageSize: number }) {
    const response = await pageRecord({ current: params.current, pageSize: params.pageSize });
    const list = response.data.data
    const hasMoreData = response.data.total >= params.pageSize * params.current;
    list.forEach(item => {
      item.beforNow = calculateDaysAgo(item.createdTime)
    })
    if (response.code === 0) {
      this.setData({
        instructList: list,
        hasMoreData,
        currentPage: 1,
        total: response.data.total,
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {

    const { globalData: { access, currentUser } } = getApp();
    this.setData({
      access,
      currentUser
    })
    if (access.showInstruct) {
      this.getInstructList({ current: this.data.currentPage, pageSize: this.data.pageSize })
    } else {
      Message.warning({
        context: this,
        offset: [20, 32],
        duration: 5000,
        content: '无权访问',
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // this.getInstructListPage({ current: this.data.currentPage, pageSize: this.data.pageSize })
    let page = wx.getStorageSync('instruct-page');
    if (page == 'detail') {
      let index = wx.getStorageSync('instruct-detail-index')
      let detailData = wx.getStorageSync('instruct-detail-data');
      const oldData = this.data.instructList[index];
      // this.setData({
      //   [`instructList[${index}].beforNow`]: '哈哈哈哈',
      // })
    } else if (page == "create") {
      let add = wx.getStorageSync('instruct-create-add')
      if (add) {
        this.getInstructList({ current: 1, pageSize: 8 })
      } else {
      }
    } else if (page == "address") {
    } else {

    }
    // if (this.data.access.showInstruct) {

    // } else {
    //   Message.warning({
    //     context: this,
    //     offset: [20, 32],
    //     duration: 5000,
    //     content: '暂无权限',
    //   });
    // }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },
  /**
  * 页面相关事件处理函数--监听用户下拉动作
  */
  onPullDownRefresh: function () {
    if (this.data.access.showInstruct) {
      this.onRefresh();
    }
  },
  async onRefresh() {
    //导航条加载动画
    wx.showNavigationBarLoading();
    //停止下拉刷新
    const response = await pageRecord({ current: 1, pageSize: 8 });
    if (response.code === 0) {
      const hasMoreData = response.data.total >= 8;
      const list = response.data.data
      list.forEach(item => {
        item.beforNow = calculateDaysAgo(item.createdTime)
      })
      this.setData({
        instructList: list,
        hasMoreData,
        currentPage: 1,
        total: response.data.total,
        pageSize: 8
      })
    }
    setTimeout(() => {
      wx.stopPullDownRefresh();
      wx.hideNavigationBarLoading();
    }, 1000);
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.setData({
      firstReachBottom: this.data.firstReachBottom + 1
    })
    if (this.data.total > this.data.pageSize) {
      wx.showLoading({
        title: '加载中...'
      })
      if (this.data.hasMoreData) {
        const nextPage = this.data.currentPage + 1;
        this.setData({
          currentPage: nextPage
        })
        this.getInstructListPage({ current: nextPage, pageSize: this.data.pageSize })
        wx.hideLoading()
      } else {
        if (this.data.firstReachBottom === this.data.currentPage) {
          wx.showToast({
            title: '已加载完成'
          })
        }
        wx.hideLoading()
      }
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})